--[[
-- Author:      feilong
-- DateTime:    2020-10-10 17:19:33
-- Description: 节点间的消息处理
    
--]]


local skynet = require "skynet"
local cjson = require "cjson"

local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor()
	self.services = {}
	self:register()	
end

--注册本服务里的消息
function MessageHandler:register()    
    g.Log():debug("i am manager register!")
    self.message_dispatch = g.MsgDis()
    self.message_dispatch:register('start', handler(self, self.start))

    self.message_dispatch:register('account.REQ_VERIFY', handler(self, self.verifyReq))
    self.message_dispatch:register('account.REQ_REGISTER_TOURIST', handler(self, self.registerTouristReq))
end

function MessageHandler:showService()  
    --加载了的服务列表
    g.Message():callService(".launcher", "LIST")
    g.Log():debug("list--> ", list, skynet.self())
end



local save_cache_script = [[
    redis.call('set',KEYS[1],ARGV[1])
    redis.call('set',KEYS[2],ARGV[2])
]]

function MessageHandler:save_data_to_cache(guid, uid)
    local guid_key = self:makeGuidKey(guid)
    local uid_key = self:makeAuidKey(uid)
    print(guid_key, uid, uid_key, guid)
    g.Message():sendService(".redis", "eval", save_cache_script, 2, guid_key, uid_key, uid, guid)
    
end

local create_uid_script = [[
    local incr_id_key = KEYS[1]
    local guid = KEYS[2]
    local guid_key = KEYS[3]
    local new_id = redis.call('incr', incr_id_key)
    new_id = tonumber(new_id) + 100000
    redis.call('set', guid_key, new_id)
    local uid_key ='account_' .. new_id
    redis.call('set', uid_key, guid)
    return new_id
]]

function MessageHandler:createUid(auid)
    local incr_id_key = self:getIncrKey()
    local guid_key = self:makeGuidKey(auid)
    local uid = g.Message():callService(".redis", "normal_cmd", "eval", create_uid_script, 3, incr_id_key, auid, guid_key)
    -- 保存到mongo
    -- local user_info = {guid = guid,uid = tonumber(uid)}
    -- g.Message():callService(".mongo", "safe_update", {_id = guid}, {['$set'] = user_info}, true)
    
    return uid
end

function MessageHandler:makeGuidKey(guid)
    return 'guid_' .. guid
end

function MessageHandler:makeAuidKey(account_id)
    return 'account_' .. account_id
end

function MessageHandler:getIncrKey()
    return 'guid_incr_key'
end

function MessageHandler:getUid(account_id)
    if account_id and type(account_id) == 'number' then
        -- local conn = self.redis_pool:get_conn_from_pool()
        local incr_id_key = self:getIncrKey()
        local guid_key = self:makeGuidKey(account_id)
        -- local uid = conn:get(guid_key)
        local uid = g.Message():callService(".redis", "normal_cmd", "get", guid_key)
        print("get_uid uid:", uid)
        if not uid then
            -- mongo_data = g.Message():callService(".mongo", "findOne", {guid = guid})
            -- if mongo_data then
            --     uid = mongo_data.uid
            --     self:save_data_to_cache(guid, uid)
            --     print(guid,"----------- find data in  mongodb")
            -- else
                uid = self:createUid(account_id)
                print(account_id, "+++++++++++ need create uid")
            -- end
        end
        return tonumber(uid)
    end

    return false
end










---------------------------------------------------------
-- CMD
---------------------------------------------------------
function MessageHandler:start()


end


--检验token
function MessageHandler:verifyReq(session, msg)

    print("_______msg__", msg)
    -- if msg then return end
    local result = {
        key_token = msg.key_token,
        channel = msg.package_channel,
        uid = msg.uid
    }
    local account_id = 1
    g.cluster_manager:sendGate(session, 'account.RSP_VERIFY', {
        uid = result.uid,
        key_token = result.key_token, 
        channel = result.channel,
        url = result.url,        
    }, account_id)
  
    return
    
    -- local matchine_token = msg.matchine_token
    -- local package_channel = msg.package_channel
    -- if #matchine_token == 0 then
    --     matchine_token = nil
    -- end
    -- local body = cjson.encode({
    --     uid = msg.uid,
    --     key_token = msg.key_token,
    --     matchine_token = matchine_token,
    --     client_ip = client_ip,
    --     package_channel = package_channel,
    --     os_system = msg.os_system,
    --     platform = msg.platform,
    -- })
    -- local exheader = {
    --     uid = msg.uid,
    --     ip = client_ip_num,
    --     channel = package_channel,
    --     os_system = msg.os_system,
    --     platform = msg.platform,
    -- }
    -- local status, body = skynet.call('.web_proxy','lua','web_post',constant.GET_TOKEN_URL,body, exheader)

    -- if status ~= 200 then
    --     return utils.send_to_gateway(0,-1,client_fd,'account.RSP_VERIFY',
    --         {result = error_code.VERIFY_ERROR_RETRY})
    -- end
    
    -- local result = cjson.decode(body)
    -- if result.code ~= 0 then
    --     local ret = error_code.VERIFY_ERROR_RETRY
    --     if result.code == -100 then
    --         ret = error_code.EXPIRED_LOGIN
    --     end

    --     if result.code == -118 or result.code == -119 or result.code == -120 then
    --         print("REQ_VERIFY---> ip or matchine limit ",result.code)
    --         return utils.send_to_gateway(0,-1,client_fd,'account.RSP_VERIFY',
    --             {result = error_code.RESTRICT_ERROR})
    --     else
    --         return utils.send_to_gateway(0,-1,client_fd,'account.RSP_VERIFY',
    --             {result = ret,channel = result.channel})
    --     end
    -- end

    -- if not result.account_id or not result.key_token then
    --     return utils.send_to_gateway(0,-1,client_fd,'account.RSP_VERIFY',
    --         {result = error_code.VERIFY_ERROR_RETRY,channel = result.channel})
    -- end

    -- dbglog(tostring_r(result))
    -- local account_id = tonumber(result.account_id)
    -- local uid = skynet.call('.guid_mgr','lua','get_uid',account_id)
    -- if not uid then
    --     return utils.send_to_gateway(0,-1,client_fd,'account.RSP_VERIFY',{result = error_code.TOURIST_REGISTER_FAIL})
    -- end

    -- return utils.send_to_gateway(0,-1,client_fd,'account.RSP_VERIFY',{
    --     uid = uid,key_token = result.key_token, channel = result.channel,url = result.url,real_channel = result.pkg_channel},uid,account_id)
end
-- end

--游客注册
function MessageHandler:registerTouristReq(session, msg)

    local matchine_token = msg.matchine_token
    local package_channel = msg.package_channel
    local os_system = msg.os_system
    local platform = msg.platform

    -- local body = cjson.encode({
    --     matchine_token = matchine_token,
    --     client_ip = client_ip,
    --     package_channel = package_channel,
    --     os_system = os_system,
    --     platform = platform,
    -- })
    -- local exheader = {
    --     ip = client_ip_num,
    --     channel = package_channel,
    --     os_system = os_system,
    --     platform = platform,
    -- }    
    -- print("___REQ_REGISTER_TOURIST____", msg, body, exheader)
    -- local status, body = skynet.call('.web_proxy','lua','web_post',constant.REGISTER_TOURIST,body, exheader)
    -- if status ~= 200 then
    --     return utils.send_to_gateway(0,-1,client_fd,'account.RSP_REGISTER_TOURIST',
    --         {result = error_code.TOURIST_REGISTER_FAIL})
    -- end
    -- local result = cjson.decode(body)
    -- if result.code ~= 0 then
    --     if result.code == -118 or result.code == -119 or result.code == -120 then
    --         print("REQ_REGISTER_TOURIST---> ip or matchine limit ",result.code)
    --         return utils.send_to_gateway(0,-1,client_fd,'account.RSP_REGISTER_TOURIST',
    --             {result = error_code.RESTRICT_ERROR})
    --     else
    --         return utils.send_to_gateway(0,-1,client_fd,'account.RSP_REGISTER_TOURIST',
    --             {result = error_code.TOURIST_REGISTER_FAIL})
    --     end
    -- end

    local result = {
        account_id = math.random(100, 10000),
        key_token = os.time() .. math.random(1, 1000),
    }

    if not result.account_id or not result.key_token then
        --注册失败消息返回gate
        g.cluster_manager:sendGate(session, 'account.RSP_REGISTER_TOURIST',
            {result = g.ErrorCode().TOURIST_REGISTER_FAIL})
        return
    end
    local account_id = result.account_id
    -- local uid = skynet.call('.guid_mgr', 'lua', 'get_uid', account_id)
    --生成uid
    local uid = self:getUid(account_id)
    if not uid then
        g.cluster_manager:sendGate(session, 'account.RSP_REGISTER_TOURIST',
            {result = g.ErrorCode().TOURIST_REGISTER_FAIL})        
        return
    end
    g.cluster_manager:sendGate(session, 'account.RSP_REGISTER_TOURIST',
        {uid = uid, key_token = result.key_token, real_channel = result.pkg_channel, url = result.url})      
end


return MessageHandler